/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { useState } from "react";
import ExcelUploader from "../components/ExcelUploader";
import JsonViewer from "../components/JsonViewer";
import ChatBox from "../components/ChatBox";


function transformData(data: { headers: any; data: any; }) {
  const headers = data.headers;
  const rows = data.data;

  // Create columns
  const columns = headers.map((header: { [x: string]: any[]; }, index: any) => {
    if (typeof header === 'object') {
      return {
        title: Object.keys(header)[0],
        dataIndex: `col${index}`,
        key: `col${index}`,
        children: header[Object.keys(header)[0]].map((subHeader: any, subIndex: any) => ({
          title: subHeader,
          dataIndex: `${index}_${subIndex}`,
          key: `${index}_${subIndex}`
        }))
      };
    } else {
      return {
        title: header,
        dataIndex: `col${index}`,
        key: `col${index}`
      };
    }
  });

  // Create dataSource
  const dataSource = rows.map((row: any[]) => {
    const rowObj = {};
    row.forEach((cell: any, cellIndex: string | number) => {
      if (headers[cellIndex] && typeof headers[cellIndex] === 'object') {
        const subHeaders = headers[cellIndex][Object.keys(headers[cellIndex])[0]];
        subHeaders.forEach((_: any, subIndex: any) => {
          (rowObj as Record<string, any>)[`${cellIndex}_${subIndex}`] = cell;
        });
      } else {
        (rowObj as Record<string, any>)[`col${cellIndex}`] = cell;
      }
    });
    return rowObj;
  });

  return { columns, dataSource };
}

export default function Home() {
  const [jsonData, setJsonData] = useState<any>(null);

  const handleExcelData = (data: any) => {
    setJsonData(data);
  };

  return (
    <div className="min-h-screen p-8">
      <h1 className="text-2xl font-bold mb-6 text-center">Excel 解析器</h1>
      <div className="flex flex-col md:flex-row gap-12">
        <div className="flex-1 flex flex-col gap-10">
          <ExcelUploader onDataParsed={handleExcelData} />
          <JsonViewer data={jsonData} />
        </div>
        <div className="w-[600px]">
          <ChatBox data={jsonData ? transformData(jsonData) : null} />
        </div>
      </div>
    </div>
  );
}
